package itpenguin.train.tokyometro;

import itpenguin.train.common.Position;
import itpenguin.train.common.Train;
import itpenguin.train.common.TrainFeed;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;

import com.google.transit.realtime.GtfsRealtime.VehiclePosition.VehicleStopStatus;

public class TokyoMetro implements TrainFeed {

	protected static final String API_KEY = "89d0c24be59183aa14a63530120470b1a002e4982a7aafdc54cdb1a8cd17e83e";
	
	@Override
	public List<Train> getCurrentPositions() throws IOException {
		
        InputStream is = new URL("https://api.tokyometroapp.jp/api/v2/datapoints?rdf:type=odpt:Train&acl:consumerKey=" + API_KEY).openStream();
		JSONArray ja = JSONArray.fromObject(IOUtils.toString(is));
		List<Train> list = new ArrayList<Train>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
		for (Object elm : ja) {
			JSONObject jo = (JSONObject) elm;
			
			Object toObj = jo.get("odpt:toStation");
			String toStation = toObj == JSONNull.getInstance() ? null : (String) toObj;
			VehicleStopStatus vss = toStation == null ? VehicleStopStatus.STOPPED_AT : VehicleStopStatus.IN_TRANSIT_TO;
			
			Position pos = Dictionary.getStationPosition(jo.getString("odpt:fromStation"));
			
			Train train;
			try {
				train = new Train(pos.getLatitude(), pos.getLongitude(), vss, jo.getString("odpt:trainNumber"), 
						jo.get("odpt:trainType") + " " + jo.get("odpt:railDirection"), (String) jo.get("odpt:railway"),
						df.parse(jo.getString("dc:date")));
			} catch (ParseException e) {
				throw new IOException(e);
			}
			train.setBoundFor(jo.getString("odpt:terminalStation"));
			train.setKind(jo.getString("odpt:trainType"));
			train.setDirection(jo.getString("odpt:railDirection"));
			list.add(train);
			
		}
		
		return list;
	}

}
